#!/bin/bash


# 获取全局 build number，文件路径通过第一个参数传入，默认 global_build_number.txt
get_global_build_number() {
    local buildNumFile="${1:-$GLOBAL_BUILD_NUMBER_FILE}"
    if [ ! -f "$buildNumFile" ]; then echo 1000 > "$buildNumFile"; fi
    local num=$(cat "$buildNumFile")
    echo $((num+1)) > "$buildNumFile"
    echo "$num"
}

# 解析 pubspec.yaml version 并计算构建号
# shellcheck disable=SC2120
parseVersion() {
  version_line=$(grep '^version:' pubspec.yaml)
  version=$(echo $version_line | awk '{print $2}' | cut -d'+' -f1)
  build_suffix=$(echo $version_line | awk '{print $2}' | cut -d'+' -f2)

  IFS='.' read -r major minor patch <<<"$version"
  version_num=$((major * 10000 + minor * 100 + patch))
  # 支持传入参数，默认为0
  extra_num=${1:-0}
  build_num=$((version_num * 1000 + build_suffix + extra_num))
  echo "$version+$build_num"
}

build() {
  pwd
   cleanEnv;

  local cmd="--no-tree-shake-icons --build-number=${APP_BUILD_NUM} --dart-define=env=${ENV_NAME}"

  echo "Building the project..."
  echo  $cmd
#  flutter build apk --release $cmd
  # flutter build ipa --release
  echo "Build completed successfully."
}

cleanEnv() {
  echo "Cleaning the environment..."
  flutter clean
  echo "Environment cleaned."
  flutter pub get
}
